<?php

/**
 * ECSHOP 商品分类页
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: testyang $
 * $Id: category.php 15013 2008-10-23 09:31:42Z testyang $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
$brand = isset($_REQUEST['brand']) && intval($_REQUEST['brand']) > 0 ? intval($_REQUEST['brand']) : 0;
$filter_attr = isset($_REQUEST['filter_attr']) && intval($_REQUEST['filter_attr']) > 0 ? intval($_REQUEST['filter_attr']) : 0;

$c_id = !empty($_GET['c_id']) ? intval($_GET['c_id']) : 0;

if ($c_id <= 0)
{
    $pcat_array = get_categories_tree();

    foreach ($pcat_array as $key => $pcat_data)
    {
        $pcat_array[$key]['name'] = encode_output($pcat_data['name']);
        if ($pcat_data['cat_id'])
        {
            foreach ($pcat_data['cat_id'] as $k => $v)
            {
                $pcat_array[$key]['cat_id'][$k]['name'] = encode_output($v['name']);
            }
        }
    }
    $smarty->assign('cat_array' , $pcat_array);
    $smarty->assign('all_cat' , 1);
}
else
{
    $cat_array = get_categories_tree($c_id);
    //var_dump($cat_array);
    $smarty->assign('c_id', $c_id);
    $cat_name = $db->getOne('SELECT cat_name FROM ' . $ecs->table('category') . ' WHERE cat_id=' . $c_id);
    $smarty->assign('cat_name', encode_output($cat_name));
    if (!empty($cat_array[$c_id]['cat_id']))
    {
        foreach ($cat_array[$c_id]['cat_id'] as $key => $child_data)
        {
            $cat_array[$c_id]['cat_id'][$key]['name'] = encode_output($child_data['name']);
        }
        $smarty->assign('cat_children', $cat_array[$c_id]['cat_id']);
    }

    if (empty($_GET['order_price']))
    {
        $order_rule = 'ORDER BY g.shop_price ASC, g.sort_order';
    }
    else
    {
        $order_rule = 'ORDER BY g.shop_price DESC, g.sort_order';
    }

    $cat_goods = assign_cat_goods($c_id, 0, 'wap', $order_rule);

    if($brand !=0)
    {
       $a = assign_wap_brand_goods($brand, 0, $c_id,$order_rule);

    }
    if($filter_attr !=0)
    {

    }
    //var_dump($cat_goods);
    $num = count($cat_goods['goods']);
    if ($num > 0)
    {
        $page_num = '10';
        $page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
        $pages = ceil($num / $page_num);
        if ($page <= 0)
        {
            $page = 1;
        }
        if ($pages == 0)
        {
            $pages = 1;
        }
        if ($page > $pages)
        {
            $page = $pages;
        }
        $i = 1;
        foreach ($cat_goods['goods'] as $goods_data)
        {
            if (($i > ($page_num * ($page - 1 ))) && ($i <= ($page_num * $page)))
            {
                $price = empty($goods_info['promote_price_org']) ? $goods_data['shop_price'] : $goods_data['promote_price'];
                //$wml_data .= "<a href='goods.php?id={$goods_data['id']}'>".encode_output($goods_data['name'])."</a>[".encode_output($price)."]<br/>";
                $data[] = array('i' => $i , 'price' => encode_output($price) , 'id' => $goods_data['id'] , 'name' => encode_output($goods_data['name']),'goods_img'=>$goods_data['goods_img']);
            }
            $i++;
        }

        $smarty->assign('goods_data', $data);

        //var_dump($data);
        $pagebar = get_wap_pager($num, $page_num, $page, 'category.php?c_id='.$c_id.'&order_price='.(empty($order_price)?0:$order_price), 'page');
        $smarty->assign('pagebar', $pagebar);
    }

    $pcat_array = get_parent_cats($c_id);

    if (!empty($pcat_array[1]['cat_name']))
    {
        $pcat_array[1]['cat_name'] = encode_output($pcat_array[1]['cat_name']);
        $smarty->assign('pcat_array', $pcat_array[1]);
    }

    $smarty->assign('cat_array', $cat_array);
}

/***分类单页 属性 start****/

/****初始化 start****/
if (isset($_REQUEST['c_id']))
{
    $cat_id = intval($_REQUEST['c_id']);
}
elseif (isset($_REQUEST['category']))
{
    $cat_id = intval($_REQUEST['category']);
}
else
{
    /* 如果分类ID为0，则返回首页 */
    ecs_header("Location: ./\n");

    exit;
}


/* 初始化分页信息 */
$page = isset($_REQUEST['page'])   && intval($_REQUEST['page'])  > 0 ? intval($_REQUEST['page'])  : 1;
//$size = isset($_CFG['page_size'])  && intval($_CFG['page_size']) > 0 ? intval($_CFG['page_size']) : 10;
$size = 1;
$brand = isset($_REQUEST['brand']) && intval($_REQUEST['brand']) > 0 ? intval($_REQUEST['brand']) : 0;
$price_max = isset($_REQUEST['price_max']) && intval($_REQUEST['price_max']) > 0 ? intval($_REQUEST['price_max']) : 0;
$price_min = isset($_REQUEST['price_min']) && intval($_REQUEST['price_min']) > 0 ? intval($_REQUEST['price_min']) : 0;
$filter_attr_str = isset($_REQUEST['filter_attr']) ? htmlspecialchars(trim($_REQUEST['filter_attr'])) : '0';

$filter_attr_str = trim(urldecode($filter_attr_str));
$filter_attr_str = preg_match('/^[\d\.]+$/',$filter_attr_str) ? $filter_attr_str : '';
$filter_attr = empty($filter_attr_str) ? '' : explode('.', $filter_attr_str);


/* 排序、显示方式以及类型 */
$default_display_type = $_CFG['show_order_type'] == '0' ? 'list' : ($_CFG['show_order_type'] == '1' ? 'grid' : 'text');
$default_sort_order_method = $_CFG['sort_order_method'] == '0' ? 'DESC' : 'ASC';
$default_sort_order_type   = $_CFG['sort_order_type'] == '0' ? 'goods_id' : ($_CFG['sort_order_type'] == '1' ? 'shop_price' : 'last_update');

$sort  = (isset($_REQUEST['sort'])  && in_array(trim(strtolower($_REQUEST['sort'])), array('goods_id', 'shop_price', 'last_update'))) ? trim($_REQUEST['sort'])  : $default_sort_order_type;
$order = (isset($_REQUEST['order']) && in_array(trim(strtoupper($_REQUEST['order'])), array('ASC', 'DESC')))                              ? trim($_REQUEST['order']) : $default_sort_order_method;
//$display  = (isset($_REQUEST['display']) && in_array(trim(strtolower($_REQUEST['display'])), array('list', 'grid', 'text'))) ? trim($_REQUEST['display'])  : (isset($_COOKIE['ECS']['display']) ? $_COOKIE['ECS']['display'] : $default_display_type);
//$display  = in_array($display, array('list', 'grid', 'text')) ? $display : 'text';
//setcookie('ECS[display]', $display, gmtime() + 86400 * 7);
/****初始化  end****/


//$cat_id = !empty($_GET['id']) ? intval($_GET['order_price']) : '';
$children = get_children($cat_id);
$cat = get_cat_info($cat_id);
//echo $cat_id;
//var_dump($cat);
/****排序 start****/
$type = !empty($_GET['type']) ? $_GET['type'] : '';
$order_sell = $order_rule = '';
$order_price = !empty($_GET['order_price']) ? intval($_GET['order_price']) : '';
$brand = isset($_REQUEST['brand']) && intval($_REQUEST['brand']) > 0 ? intval($_REQUEST['brand']) : 0;

$temp_type=array();
$temp_type=array('best','promote','hot','new');
if(!in_array($type,$temp_type))
{
    $type='';
}
$_GET['type']=$type;



if ($type != 'best' && $type != 'promote' && $type != 'hot' && $type != 'new')
{
    $type = '';
}
$smarty->assign('type', $type);

/***销量排序 start***/
if($order_price ==3)
{
    $order_sell = 1;
}
elseif($order_price ==4)
{
    $order_sell = 0;
}
/***销量排序 end***/

elseif ($order_price==2)
{
    $order_rule = 'ORDER BY shop_price ASC';
}
elseif($order_price==1)
{
    $order_rule = 'ORDER BY shop_price DESC';
}


if($type=='')
{
    $goods=wap_get_all_goods($order_rule,$order_sell,$brand);  //销售排序修改（需修改）
}
elseif ($type == 'promote')
{
    $goods = wap_get_promote_goods($order_rule,$order_sell);  //销售排序修改
}
else
{
    $goods = wap_get_recommend_goods($type, $order_rule,$order_sell);  //销售排序修改
}

$num = count($goods);

if ($num > 0)
{
    foreach ($goods as $key => $data)
    {
        $sort_array[$data['id']] = $key;
    }
    $page_num = '6';
    $page = !empty($_GET['page']) ? intval($_GET['page']) : 1;
    $_GET['page']=$page;
    $pages = ceil($num / $page_num);


    if ($page <= 0)
    {
        $page = 1;
    }
    if ($pages == 0)
    {
        $pages = 1;
    }
    if ($page > $pages)
    {
        $page = $pages;
    }
    $i = 1;
}
/*****排序  end****/

/**价格 start***/

/* 获取价格分级 */
//echo $cat['grade'];
//echo $cat['parent_id'];
if ($cat['grade'] == 0  && $cat['parent_id'] != 0)
{
    //echo 111;
    $cat['grade'] = get_parent_grade($cat_id); //如果当前分类级别为空，取最近的上级分类
    //var_dump($cat['grade']);

}

if ($cat['grade'] > 1)
{
    /* 需要价格分级 */

    /*
        算法思路：
            1、当分级大于1时，进行价格分级
            2、取出该类下商品价格的最大值、最小值
            3、根据商品价格的最大值来计算商品价格的分级数量级：
                    价格范围(不含最大值)    分级数量级
                    0-0.1                   0.001
                    0.1-1                   0.01
                    1-10                    0.1
                    10-100                  1
                    100-1000                10
                    1000-10000              100
            4、计算价格跨度：
                    取整((最大值-最小值) / (价格分级数) / 数量级) * 数量级
            5、根据价格跨度计算价格范围区间
            6、查询数据库

        可能存在问题：
            1、
            由于价格跨度是由最大值、最小值计算出来的
            然后再通过价格跨度来确定显示时的价格范围区间
            所以可能会存在价格分级数量不正确的问题
            该问题没有证明
            2、
            当价格=最大值时，分级会多出来，已被证明存在
    */

    $sql = "SELECT min(g.shop_price) AS min, max(g.shop_price) as max ".
        " FROM " . $ecs->table('goods'). " AS g ".
        " WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1  ';
    //获得当前分类下商品价格的最大值、最小值

    $row = $db->getRow($sql);

    // 取得价格分级最小单位级数，比如，千元商品最小以100为级数
    $price_grade = 0.0001;
    for($i=-2; $i<= log10($row['max']); $i++)
    {
        $price_grade *= 10;
    }

    //跨度
    $dx = ceil(($row['max'] - $row['min']) / ($cat['grade']) / $price_grade) * $price_grade;
    if($dx == 0)
    {
        $dx = $price_grade;
    }

    for($i = 1; $row['min'] > $dx * $i; $i ++);

    for($j = 1; $row['min'] > $dx * ($i-1) + $price_grade * $j; $j++);
    $row['min'] = $dx * ($i-1) + $price_grade * ($j - 1);

    for(; $row['max'] >= $dx * $i; $i ++);
    $row['max'] = $dx * ($i) + $price_grade * ($j - 1);

    $sql = "SELECT (FLOOR((g.shop_price - $row[min]) / $dx)) AS sn, COUNT(*) AS goods_num  ".
        " FROM " . $ecs->table('goods') . " AS g ".
        " WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 '.
        " GROUP BY sn ";

    $price_grade = $db->getAll($sql);

    foreach ($price_grade as $key=>$val)
    {
        $temp_key = $key + 1;
        $price_grade[$temp_key]['goods_num'] = $val['goods_num'];
        $price_grade[$temp_key]['start'] = $row['min'] + round($dx * $val['sn']);
        $price_grade[$temp_key]['end'] = $row['min'] + round($dx * ($val['sn'] + 1));
        $price_grade[$temp_key]['price_range'] = $price_grade[$temp_key]['start'] . '&nbsp;-&nbsp;' . $price_grade[$temp_key]['end'];
        $price_grade[$temp_key]['formated_start'] = price_format($price_grade[$temp_key]['start']);
        $price_grade[$temp_key]['formated_end'] = price_format($price_grade[$temp_key]['end']);
        $price_grade[$temp_key]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_grade[$temp_key]['start'], 'price_max'=> $price_grade[$temp_key]['end'], 'filter_attr'=>$filter_attr_str), $cat['cat_name']);

        /* 判断价格区间是否被选中 */
        if (isset($_REQUEST['price_min']) && $price_grade[$temp_key]['start'] == $price_min && $price_grade[$temp_key]['end'] == $price_max)
        {
            $price_grade[$temp_key]['selected'] = 1;
        }
        else
        {
            $price_grade[$temp_key]['selected'] = 0;
        }
    }

    $price_grade[0]['start'] = 0;
    $price_grade[0]['end'] = 0;
    $price_grade[0]['price_range'] = $_LANG['all_attribute'];
    $price_grade[0]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>0, 'price_max'=> 0, 'filter_attr'=>$filter_attr_str), $cat['cat_name']);
    $price_grade[0]['selected'] = empty($price_max) ? 1 : 0;

    $smarty->assign('price_grade',     $price_grade);

   // var_dump($price_grade);
}

/**价格 end***/


/* 品牌筛选 start*/
$sql = "SELECT b.brand_id, b.brand_name, COUNT(*) AS goods_num ".
    "FROM " . $GLOBALS['ecs']->table('brand') . "AS b, ".
    $GLOBALS['ecs']->table('goods') . " AS g LEFT JOIN ". $GLOBALS['ecs']->table('goods_cat') . " AS gc ON g.goods_id = gc.goods_id " .
    "WHERE g.brand_id = b.brand_id AND ($children OR " . 'gc.cat_id ' . db_create_in(array_unique(array_merge(array($cat_id), array_keys(cat_list($cat_id, 0, false))))) . ") AND b.is_show = 1 " .
    " AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ".
    "GROUP BY b.brand_id HAVING goods_num > 0 ORDER BY b.sort_order, b.brand_id ASC";

$brands = $GLOBALS['db']->getAll($sql);

foreach ($brands AS $key => $val)
{
    $temp_key = $key + 1;
    $brands[$temp_key]['brand_name'] = $val['brand_name'];
    $brands[$temp_key]['url'] = build_uri('category', array('cid' => $cat_id, 'bid' => $val['brand_id'], 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str), $cat['cat_name']);

    /* 判断品牌是否被选中 */
    if ($brand == $brands[$key]['brand_id'])
    {
        $brands[$temp_key]['selected'] = 1;
    }
    else
    {
        $brands[$temp_key]['selected'] = 0;
    }
   // $brands[$temp_key]['url'] = "goods_list.php?type=$type&order_price=$order_price&page=$page&brand=" . $val['brand_id'];
}

$brands[0]['brand_name'] = $_LANG['all_attribute'];
$brands[0]['url'] = build_uri('category', array('cid' => $cat_id, 'bid' => 0, 'price_min'=>$price_min, 'price_max'=> $price_max, 'filter_attr'=>$filter_attr_str), $cat['cat_name']);
$brands[0]['selected'] = empty($brand) ? 1 : 0;
//$brands[0]['url'] = "category.php?type=$type&order_price=$order_price&page=$page";
//
$smarty->assign('brands', $brands);
/* 品牌筛选 end*/


/***属性筛选 start***/

$ext = ''; //商品查询条件扩展
if ($cat['filter_attr'] > 0)
{
    $cat_filter_attr = explode(',', $cat['filter_attr']);       //提取出此分类的筛选属性
    $all_attr_list = array();
//var_dump($cat_filter_attr);
    foreach ($cat_filter_attr AS $key => $value)
    {
        $sql = "SELECT a.attr_name FROM " . $ecs->table('attribute') . " AS a, " . $ecs->table('goods_attr') . " AS ga, " . $ecs->table('goods') . " AS g WHERE ($children OR " . get_extension_goods($children) . ") AND a.attr_id = ga.attr_id AND g.goods_id = ga.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND a.attr_id='$value'";
        //echo $sql;
        if($temp_name = $db->getOne($sql))
        {
            //echo $temp_name;
            $all_attr_list[$key]['filter_attr_name'] = $temp_name;

            $sql = "SELECT a.attr_id, MIN(a.goods_attr_id ) AS goods_id, a.attr_value AS attr_value FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods') .
                " AS g" .
                " WHERE ($children OR " . get_extension_goods($children) . ') AND g.goods_id = a.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 '.
                " AND a.attr_id='$value' ".
                " GROUP BY a.attr_value";
            $attr_list = $db->getAll($sql);

            //var_dump($attr_list);
            $temp_arrt_url_arr = array();

            for ($i = 0; $i < count($cat_filter_attr); $i++)        //获取当前url中已选择属性的值，并保留在数组中
            {
                $temp_arrt_url_arr[$i] = !empty($filter_attr[$i]) ? $filter_attr[$i] : 0;
            }

            $temp_arrt_url_arr[$key] = 0;                           //“全部”的信息生成
            $temp_arrt_url = implode('.', $temp_arrt_url_arr);
            $all_attr_list[$key]['attr_list'][0]['attr_value'] = $_LANG['all_attribute'];
            $all_attr_list[$key]['attr_list'][0]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url), $cat['cat_name']);
            $all_attr_list[$key]['attr_list'][0]['selected'] = empty($filter_attr[$key]) ? 1 : 0;

            foreach ($attr_list as $k => $v)
            {
                $temp_key = $k + 1;
                $temp_arrt_url_arr[$key] = $v['goods_id'];       //为url中代表当前筛选属性的位置变量赋值,并生成以‘.’分隔的筛选属性字符串
                $temp_arrt_url = implode('.', $temp_arrt_url_arr);

                $all_attr_list[$key]['attr_list'][$temp_key]['attr_value'] = $v['attr_value'];
                $all_attr_list[$key]['attr_list'][$temp_key]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_min, 'price_max'=>$price_max, 'filter_attr'=>$temp_arrt_url), $cat['cat_name']);

                if (!empty($filter_attr[$key]) AND $filter_attr[$key] == $v['goods_id'])
                {
                    $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 1;
                }
                else
                {
                    $all_attr_list[$key]['attr_list'][$temp_key]['selected'] = 0;
                }

            }

        }

    }
   //var_dump($all_attr_list);
    //var_dump($all_attr_list[0]['attr_list']);
    $smarty->assign('filter_attr_list',  $all_attr_list);
    /* 扩展商品查询条件 */
    if (!empty($filter_attr))
    {
        $ext_sql = "SELECT DISTINCT(b.goods_id) FROM " . $ecs->table('goods_attr') . " AS a, " . $ecs->table('goods_attr') . " AS b " .  "WHERE ";
        $ext_group_goods = array();

        foreach ($filter_attr AS $k => $v)                      // 查出符合所有筛选属性条件的商品id */
        {
            if (is_numeric($v) && $v !=0 &&isset($cat_filter_attr[$k]))
            {
                $sql = $ext_sql . "b.attr_value = a.attr_value AND b.attr_id = " . $cat_filter_attr[$k] ." AND a.goods_attr_id = " . $v;
                $ext_group_goods = $db->getColCached($sql);
                $ext .= ' AND ' . db_create_in($ext_group_goods, 'g.goods_id');
            }
        }
    }
}

/******属性筛选  end****/


function get_cat_info($cat_id)
{
    return $GLOBALS['db']->getRow('SELECT cat_name, keywords, cat_desc, style, grade, filter_attr, parent_id FROM ' . $GLOBALS['ecs']->table('category') .
        " WHERE cat_id = '$cat_id'");
}

/****分类单页 属性  end*****/

$smarty->assign('footer', get_footer());
$smarty->display('goods_list.html');


/******排序相关函数  start****/
/**
 * 获得所有商品
 *
 * @access  public
 * @param   string      $order_rule     指定商品排序规则
 * @return  array
 */
function wap_get_all_goods($order_rule = '',$order_sell = '', $brand = '')
{
    $time = gmtime();

    /* 取得促销lbi的数量限制 */
    $sql = 'SELECT g.goods_id, g.goods_name, g.goods_name_style, g.market_price, g.shop_price AS org_price, g.promote_price, ' .
        "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS shop_price, ".
        "promote_start_date, promote_end_date, g.goods_brief, g.goods_thumb, goods_img, b.brand_name, " .
        "g.is_best, g.is_new, g.is_hot, g.is_promote, RAND() AS rnd " .
        'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' .
        'LEFT JOIN ' . $GLOBALS['ecs']->table('brand') . ' AS b ON b.brand_id = g.brand_id ' .
        "LEFT JOIN " . $GLOBALS['ecs']->table('member_price') . " AS mp ".
        "ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
        'WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 ';

    if ($brand > 0)
    {
        $sql .=  " AND g.brand_id = $brand ";
    }
    //echo $sql;
    $order_rule = empty($order_rule) ? '' : $order_rule;
    $sql .= $order_rule;
    $result = $GLOBALS['db']->getAll($sql);
    $other_goods = array();
    $goods = array();
    foreach ($result AS $idx => $row)
    {
        if ($row['promote_price'] > 0)
        {
            $promote_price = bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
            $goods[$idx]['promote_price'] = $promote_price > 0 ? price_format($promote_price) : '';
        }
        else
        {
            $goods[$idx]['promote_price'] = '';
        }

        $goods[$idx]['id']           = $row['goods_id'];
        $goods[$idx]['name']         = $row['goods_name'];
        $goods[$idx]['brief']        = $row['goods_brief'];
        $goods[$idx]['brand_name']   = $row['brand_name'];
        $goods[$idx]['goods_style_name']   = add_style($row['goods_name'],$row['goods_name_style']);
        $goods[$idx]['short_name']   = $GLOBALS['_CFG']['goods_name_length'] > 0 ? sub_str($row['goods_name'], $GLOBALS['_CFG']['goods_name_length']) : $row['goods_name'];
        $goods[$idx]['short_style_name']   = add_style($goods[$idx]['short_name'],$row['goods_name_style']);
        $goods[$idx]['market_price'] = price_format($row['market_price']);
        $goods[$idx]['shop_price']   = price_format($row['shop_price']);
        $goods[$idx]['thumb']        = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $goods[$idx]['goods_img']    = get_image_path($row['goods_id'], $row['goods_img']);
        $goods[$idx]['url']          = build_uri('goods', array('gid' => $row['goods_id']), $row['goods_name']);
        $goods[$idx]['sell_count']   = selled_count($row['goods_id']); //销售排序添加
        $other_goods[$idx] = $goods[$idx]['sell_count'];
    }
}
/*****排序相关函数  end****/

/**
 * 取得最近的上级分类的grade值
 *
 * @access  public
 * @param   int     $cat_id    //当前的cat_id
 *
 * @return int
 */
function get_parent_grade($cat_id)
{
    static $res = NULL;

    if ($res === NULL)
    {
        $data = read_static_cache('cat_parent_grade');
        if ($data === false)
        {
            $sql = "SELECT parent_id, cat_id, grade ".
                " FROM " . $GLOBALS['ecs']->table('category');
            $res = $GLOBALS['db']->getAll($sql);
            write_static_cache('cat_parent_grade', $res);
        }
        else
        {
            $res = $data;
        }
    }

    if (!$res)
    {
        return 0;
    }

    $parent_arr = array();
    $grade_arr = array();

    foreach ($res as $val)
    {
        $parent_arr[$val['cat_id']] = $val['parent_id'];
        $grade_arr[$val['cat_id']] = $val['grade'];
    }

    while ($parent_arr[$cat_id] >0 && $grade_arr[$cat_id] == 0)
    {
        $cat_id = $parent_arr[$cat_id];
    }

    return $grade_arr[$cat_id];

}
?>